#include "sessionmanager.h"
#include "session.h"

SessionManager *SessionManager::m_instance = 0;

QMutex SessionManager::m_mutex;

SessionManager::SessionManager()
{
    //m_mutex =
    if(m_sessionList == NULL)
    {

        m_sessionList = new QMap<int, Session*>();
    }

   // m_mutex = new QMutex();
}

SessionManager::~SessionManager()
{
    //delete m_mutex;

    if(m_sessionList != NULL)
    {
        if(!m_sessionList->empty())
        {
            QMap<int,  Session*>::iterator i = m_sessionList->begin();
            QMap<int,  Session*>::iterator j = i;
            while( i != m_sessionList->end())
            {
                j = m_sessionList->erase(i);
                delete i.value();

                i = j;
            }
            // remove error
        }

        delete m_sessionList;
    }
}

int SessionManager::removeSession(int session_id)
{
    QMutexLocker locker(&m_mutex);

    QMap<int,  Session*>::iterator i = m_sessionList->find(session_id);
    if( i == m_sessionList->end())
    {
        return -1;
    }
    int count = m_sessionList->remove(session_id);
    if(count >1)
    {
        // 2 more has same session id
        // can not happen
        return -2;
    }

    delete i.value();
    return 0;
}

int SessionManager::addSession( Session *session)
{
    QMutexLocker locker(&m_mutex);

    if(m_sessionList == NULL)
    {
        return -1;
    }

    QMap<int,  Session*>::iterator i = m_sessionList->find(session->getSessionID());
    if(i != m_sessionList->end())
    {
        //check why has same id
        // this can not happen
        return -1;
    }

    m_sessionList->insert(session->getSessionID(), session);
    return 0;
}

Session *SessionManager::getSessionByID(int session_id)
{
    if(m_sessionList != NULL)
    {
        return (*m_sessionList)[session_id];
    }

    return NULL;
}

bool SessionManager::hasSessionRunning()
{
}


Session *SessionManager::getSessionByFrom(const std::string from)
{
    if(m_sessionList != NULL)
    {
        if(!m_sessionList->empty())
        {
            QMap<int,  Session*>::iterator i = m_sessionList->begin();
            //QMap<int,  Session*>::iterator j = i;
            while( i != m_sessionList->end())
            {
                if(i.value()->getRemoteUri() == from)
                {
                    return i.value();
                }
                ++i;
            }
            // remove error
        }
    }
}
